import axios, { type AxiosResponse, type Method, type AxiosInstance, type AxiosError } from 'axios'

import { useUserStore } from '@/stores'
import { useRouter, useRoute } from 'vue-router'
import { showFailToast } from 'vant'

const timeout = 10000
const baseURL = 'https://consult-api.itheima.net/'
const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL,
  timeout
})

instance.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const userStore = useUserStore()
    if (userStore.user?.token && config.headers) {
      config.headers.Authorization = `Bearer ${userStore.user.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res: AxiosResponse) => {
    // TODO 3. 处理业务失败
    if (res.data.code !== 10000) {
      showFailToast(res.data.message || '业务失败')
      return Promise.reject(res.data)
    }
    // TODO 4. 摘取核心响应数据
    return res.data
  },
  (err: AxiosError) => {
    // TODO 5. 处理401错误
    if (err.response?.status === 401) {
      const userStore = useUserStore()
      userStore.delUser()
      const router = useRouter()
      router.push({ path: '/login', query: { returnUrl: router.currentRoute.value.fullPath } })
    }
    return Promise.reject(err)
  }
)

export type Data<T> = {
  code: number
  message: string
  data: T
}

export default instance

export const request = <T>(url: string, method: Method = 'get', submitData?: object) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method?.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
